<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Models\Favs;

class FavsController extends BaseController
{
    //添加收藏
    public function add(Request $request){
         //表单验证
        try {
            $postData = $this->validate($request, [
                'openid' => 'required',
                'fang_id' => 'required|numeric'
            ]);
            //进行入库操作
            //1:查询此用户是否对此房源有过收藏
            $data = Favs::where('openid',$postData['openid'])->where('fang_id',$postData['fang_id'])->first();
            //如果没有收藏就进行添加操作
            if(is_null($data)){
                 $data = Favs::create($postData);
            }else{
                //如果有过收藏的话，就更新最新的更新时间
                Favs::where('openid',$postData['openid'])->where('fang_id',$postData['fang_id'])->update($postData);
            }
            //更新或者添加完成  返回对应的结果
            return response()->json(['status' => 0,'msg' => '添加成功','data'=>$data]);
        }catch (\Exception $exception){
            return ['status' => 10010,'msg' => '数据验证不通过'];
        }
    }


    //查询是否收藏
    public function find(Request $request){
        $id = $request->get('id');
        $openid = $request->get('openid');
        $find = Favs::where('fang_id',$id)->where('openid',$openid)->first();
        //就代表已经找到了
        if($find){
            return ['status' => 1,'msg' => '取消收藏'];
        }else{
            return ['status' => -1,'msg' => '添加收藏'];
        }
    }


    //取消收藏
    public function del(Request $request){
        $id = $request->get('id');
        $openid = $request->get('openid');
        $find = Favs::withTrashed()->where('fang_id',$id)->where('openid',$openid)->first();
        //强制删除
        Favs::withTrashed()->find($find['id'])->forceDelete();
        return ['status' => 0,'msg' => '删除成功'];
    }

    
}
